/**
 * Copyright (C) 2013 Inera AB (http://www.inera.se)
 *
 * This file is part of Inera Axel (http://code.google.com/p/inera-axel).
 *
 * Inera Axel is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Inera Axel is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */
package se.inera.axel.shs.camel;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.TypeConversionException;
import se.inera.axel.shs.exception.ShsException;
import se.inera.axel.shs.processor.ShsExceptionConverter;
import se.inera.axel.shs.mime.DataPart;
import se.inera.axel.shs.mime.ShsMessage;
import se.inera.axel.shs.xml.management.ShsManagement;

import java.io.InputStream;


public class ThrowExceptionOnShsErrorProcessor implements Processor {

	@Override
	public void process(Exchange exchange) {

		ShsException shsException = null;
        try {
		    ShsMessage shsMessage = exchange.getIn().getBody(ShsMessage.class);
		    shsException = ShsExceptionConverter.toShsException(shsMessage);
        } catch (TypeConversionException e) {
            // ignore
        }

		if (shsException != null) {
			throw shsException;
		}

        try {
		    DataPart dataPart = exchange.getIn().getBody(DataPart.class);
		    shsException = ShsExceptionConverter.toShsException(dataPart);
        } catch (TypeConversionException e) {
            // Ignore
        }

		if (shsException != null) {
			throw shsException;
		}

        ShsManagement management;

        try {
		    management = exchange.getIn().getBody(ShsManagement.class);
		    shsException = ShsExceptionConverter.toShsException(management);
        } catch (TypeConversionException e) {
            // ignore
        }

		if (shsException != null) {
			throw shsException;
		}

        try {
		    InputStream xml = exchange.getIn().getBody(InputStream.class);
		    management = XmlConverter.convertStreamToShsManagement(xml);
		    shsException = ShsExceptionConverter.toShsException(management);
        } catch (TypeConversionException e) {
            // ignore
        }

		if (shsException != null) {
			throw shsException;
		}
	}
}
